/**
 * 
 */
package com.app.util;

import java.util.HashMap;
import java.util.Map;

import com.app.exception.DCacheException;

/**
 * @author lisong
 * @version 2012-8-14 上午9:18:23
 */
public class ClassTableUtil {

	public static int MYSQL_TABLENAME_LIMIT = 64;
	
	private static Map<String, String> tables = new HashMap<String, String>();

	/**
	 * 在系统启动获取所有table注解的类时 加载进来
	 * @param clz
	 * @param tableName
	 */
	public static void cacheClassNameToTableName(Class<?> clz,String tableName){
		if(StringUtils.isNullOrEmpty(tableName)) {
			tableName = clz.getName();
		}
		int nameLength = tableName.length();
		if(nameLength > MYSQL_TABLENAME_LIMIT) {
			throw new DCacheException("table name too long:"+tableName);
		}
		if(tables.containsValue(tableName)) {
			throw new DCacheException("table name duplicate:"+tableName);
		}
		tables.put(clz.getName(), tableName);
	}
	
	public static String getTableName(String className) {
		String tableName = tables.get(className); 
		if(StringUtils.isNullOrEmpty(tableName)) {
			throw new DCacheException("unknown table classname:"+className);
		}
		return tableName;
	}
	
	public static void main(String[] args) {
		String tableName = "asdf_asdf_a";
		String tmp = tableName;
		int index = tableName.lastIndexOf("_"); 
		if(index != -1) {
			tmp = tableName.substring(index + 1,tableName.length());
		}
		System.out.println(tmp);
	}
	
	public static String transTableColumnType(Class<?> clz,int length) {
		String ret = null;
		String indexType = clz.getSimpleName();
		if (indexType.equalsIgnoreCase("string") || indexType.equalsIgnoreCase("char")) {
			ret = "varchar("+length+")";
		} else if (indexType.equalsIgnoreCase("integer") || indexType.equalsIgnoreCase("int") || indexType.equalsIgnoreCase("short")) {
			ret = "int(11)";
		} else if (indexType.equalsIgnoreCase("float")) {
			ret = "float";
		} else if (indexType.equalsIgnoreCase("double")) {
			ret = "double";
		} else if (indexType.equalsIgnoreCase("long")) {
			ret = "bigint(20)";
		} else if (indexType.equalsIgnoreCase("boolean")) {
			ret = "tinyint(4)";
		}else {
			ret = "blob";
		}
		return ret;
	}
}
